/**
  ETFDAQ Project -- online from ETFAna Online by SUN Yazhou
  \class TAClient
  \brief client for communication among different hosts on the Internet
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2023-06-21
  \date 2023-06-25 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                    </tr>
  <tr>  <td>2023-06-21   <td>Asia Sun    <td>file created                   </tr>
  </table>

  \copyright Copyright (c) 2021-2024 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <iostream>
#include <unistd.h> // for compatibility with older linux versions
#include "TAClient.h"
#include "TAQueue.h"
#include "TAMsg.h"

using std::cout;
using std::endl;

TAClient::TAClient(){}
/// establish connection with ip:port
TAClient::TAClient(const string &ip, short port, DaqType daqType, int nshm)
 : TAVClient(ip, port, daqType), fNShm(nshm){
  fQueue = new TAQueue(daqType);
} // end ctor

TAClient::~TAClient(){
  Close();
} // end dtor

// receive data from sock of size bytes and dispose it
void TAClient::recv(){
  while(!fQueue->Add(fd)) usleep(10);
  for(auto &p : fShms) p->write(fQueue->ItemIn()->buf);
} // end member function recv

void TAClient::Initialize(){
  // porting out to an shm for others to use //
  char shm[128];
  for(int i = 0; i < fNShm; i++){
    sprintf(shm, "TAanaC_%s%d", fDaqType == kPXI ? "pxi" : "vme", i);
    fShms.push_back(new TAReadShm(shm, fDaqType, true)); // true: create shm
  } // end for over shms
  TAVClient::Initialize(); // initiate the reading thread - has to run after fShms
} // end member function Initialize

void TAClient::Close(){
  for(auto &p : fShms) if(p){ delete p; p = nullptr; }
} // end member function Close
